package logic

import (
	"context"
	"errors"
	"fmt"
	"novel-mgr1/cache"
	"novel-mgr1/model"
	"novel-mgr1/pkg"

	"novel-mgr1/userrpc/internal/svc"
	"novel-mgr1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User
	if err := findUser.FindUserByMobile(model.DB, in.Mobile); err != nil {
		return nil, err
	}
	user := model.User{
		Mobile:   in.Mobile,
		Password: pkg.Str(in.Password),
		Nickname: fmt.Sprintf("wx%v", in.Mobile[:3]+"****"+in.Mobile[7:]),
		HeadImg:  "http://t4kaai1ut.hn-bkt.clouddn.com",
	}
	if findUser.ID == 0 {
		if err := user.UserAdd(model.DB); err != nil {
			return nil, errors.New("注册失败")
		}
	} else {
		if in.LoginTypes == 1 {
			if findUser.Password != pkg.Str(in.Password) {
				return nil, errors.New("密码错误")
			}
		} else if in.LoginTypes == 2 {
			result, _ := cache.Rdb.Get(l.ctx, "sms"+in.Mobile).Result()
			if result == "" {
				return nil, errors.New("请发送验证码")
			}
			if result != in.SandSmsCode {
				return nil, errors.New("验证码错误")
			}
		}
	}

	return &userrpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
